package handler

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gorilla/websocket"
	"strconv"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/pkg/e"
	)

//业务需要实现的抽象接口
type Service interface {
	handleMsg(date model.Request, clientId string) model.Response
}

// ServiceHolder 来保存map的结构体
type ServiceHolder struct {
	M map[int]Service
}

//全局变量
var Holder *ServiceHolder

// RegisterService 注册服务
func (this *ServiceHolder) RegisterService(mtype int, service Service) (err error) {
	_, ok := this.M[mtype]
	if ok {
		fmt.Println("service has been registered :", mtype)
	} else {
		fmt.Println("success register :", mtype)
		this.M[mtype] = service
	}
	return
}

//  Start 服务启动
func (this *ServiceHolder) Start(mtype int, data model.Request, outChan chan model.Response, clientId string) {
	if value, ok := this.M[mtype]; ok {
		result := value.handleMsg(data, clientId)
		outChan <- result
		//conn.WriteMessage(result)
	}
}

//  Start 登录验证服务启动
func (this *ServiceHolder) Login(mtype int, data model.Request, conn *websocket.Conn) (clientId string, err error) {
	if value, ok := this.M[mtype]; ok {
		//下载模块初始化
		result := model.Response{}
		if mtype == 1 {
			clientId = data.Data.Sn
			result = value.handleMsg(data, data.Data.Sn)
		} else if mtype == 2 { //app初始化
			clientId = data.Data.Token
			result = value.handleMsg(data, data.Data.Token)
			jsonRequestData,_ := json.Marshal(data)
			e.Log("info",string(jsonRequestData))

		}

		conn.WriteJSON(result)
		if result.Status != 1 {
			jsonRequestData,_ := json.Marshal(data)
			e.Log("Info", string(jsonRequestData))
			jsonData,_ := json.Marshal(result)
			e.Log("Info", string(jsonData))
			err = errors.New(clientId+":登录验证失败")
		}
	}
	return
}

func ReturnErr(mid int, mtype int, info string) model.Response {
	return model.Response{
		Mid:    mid,
		Mtype:  mtype,
		Info:   strconv.Itoa(mtype) + "_" + info,
		Status: constvar.StatusErr,
	}
}
